package com.example.personalizededucationsystem.service;

import com.example.personalizededucationsystem.dto.dto.DynamicQuestionRequestDto;
import com.example.personalizededucationsystem.dto.dto.DynamicQuestionResponseDto;
import com.example.personalizededucationsystem.dto.dto.ExplanationRequestDto;
import com.example.personalizededucationsystem.dto.dto.ExplanationResponseDto;
import com.example.personalizededucationsystem.model.AnswerRecord;
import com.example.personalizededucationsystem.model.ErrorNotebook;
import com.example.personalizededucationsystem.model.Question;
import com.example.personalizededucationsystem.model.User;
import com.example.personalizededucationsystem.repository.AnswerRecordRepository;
import com.example.personalizededucationsystem.repository.ErrorNotebookRepository;
import jakarta.persistence.EntityNotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

import java.nio.file.AccessDeniedException;

@Service
public class AIAssistanceService {

    private final WebClient webClient;
    private final AnswerRecordRepository answerRecordRepository;
    private final ErrorNotebookRepository errorNotebookRepository;

    @Autowired
    public AIAssistanceService(WebClient webClient, AnswerRecordRepository answerRecordRepository, ErrorNotebookRepository errorNotebookRepository) {
        this.webClient = webClient;
        this.answerRecordRepository = answerRecordRepository;
        this.errorNotebookRepository = errorNotebookRepository;
    }

    public String getExplanationForError(long errorId, User user) throws AccessDeniedException {

        ErrorNotebook errorRecord = errorNotebookRepository.findById(errorId)
                .orElseThrow(() -> new EntityNotFoundException("错题记录未找到"));

        if (!errorRecord.getStudent().getUserId().equals(user.getUserId())) {
            throw new AccessDeniedException("您无权查看此错题的解析");
        }

        Question question = errorRecord.getQuestion();

        String studentAnswer = answerRecordRepository.findFirstByStudentAndQuestionOrderByAnsweredAtDesc(
                        errorRecord.getStudent(), question)
                .map(AnswerRecord::getUserAnswer)
                .orElse("学生未提供答案");

        ExplanationRequestDto requestDto = new ExplanationRequestDto(
                question.getContent(),
                question.getOptions(),
                question.getAnswer(),
                studentAnswer
        );

        ExplanationResponseDto response = webClient.post()
                .uri("/ai/explanation")
                .bodyValue(requestDto)
                .retrieve()
                .bodyToMono(ExplanationResponseDto.class)
                .block();

        if (response != null) {
            return response.explanation();
        } else {
            throw new RuntimeException("未能从 AI 服务获取解析");
        }
    }

    /**
     * 新增: 调用 Python 服务生成新题目
     */
    public DynamicQuestionResponseDto generateQuestionFromAI(String knowledgePointName, String subject, String type, float difficulty) {
        DynamicQuestionRequestDto request = new DynamicQuestionRequestDto(knowledgePointName, subject, type, difficulty);

        return webClient.post()
                .uri("/ai/generate-question")
                .bodyValue(request)
                .retrieve()
                .bodyToMono(DynamicQuestionResponseDto.class)
                .onErrorResume(error -> {
                    System.err.println("调用AI出题服务失败: " + error.getMessage());
                    return Mono.empty();
                })
                .block();
    }
}